package com.mayee.me.gateway.filter;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;

import java.util.Objects;

/**
 * @program: micro-service
 * @description:
 * @author: Bobby.Ma
 * @create: 2021-01-09 11:04
 **/
public class RequestDecorator extends ServerHttpRequestDecorator {

    private Flux<DataBuffer> body;

    public RequestDecorator(ServerHttpRequest delegate) {
        super(delegate);
    }

    public RequestDecorator(ServerHttpRequest delegate, Flux<DataBuffer> body) {
        super(delegate);
        this.body = body;
    }

    /**
     * change content-length
     *
     * @return
     */
    @Override
    public HttpHeaders getHeaders() {
        HttpHeaders headers = super.getHeaders();
        if (Objects.equals(headers.getContentType(), MediaType.APPLICATION_FORM_URLENCODED)) {
            if (headers.getContentLength() <= 0) {
                headers.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
            }
        }
        return headers;
    }

    /**
     * read bytes to Flux<Databuffer>
     *
     * @return
     */
    @Override
    public Flux<DataBuffer> getBody() {
        if (Objects.nonNull(body)) {
            return body;
        }
        return super.getBody();
    }

    @Override
    public MultiValueMap<String, HttpCookie> getCookies() {
        return super.getCookies();
    }
}
